package org.example.config;

import com.bianmaba.spring.security.basic.details.CurrentUserDetails;
import com.bianmaba.spring.security.basic.details.UserDetailsServiceImpl;
import com.bianmaba.spring.security.ldap.configuration.LdapContextToUserDetailsMapper;
import org.apache.commons.lang3.time.DateUtils;
import org.example.bean.entity.authorization.User;
import org.example.service.authorization.user.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.time.Duration;
import java.util.Collection;
import java.util.Date;
import java.util.UUID;

/**
 * @program: example-spring-boot-extend
 * @description:
 * @author: Chenjiabin
 * @create: 2019/9/26 10:11
 **/

@Configuration
public class CustomUserDetailsMapper extends LdapContextToUserDetailsMapper {
    @Autowired
    protected UserDetailsServiceImpl userDetailsService;
    @Autowired
    private IUserService userService;

    @Autowired
    private RedisTemplate redisTemplate;


    public CustomUserDetailsMapper() {
        System.out.println();
    }

    @Override
    public UserDetails mapUserFromContext(DirContextOperations dirContextOperations, String username, Collection<? extends GrantedAuthority> grantedAuthorities) {
        CurrentUserDetails userDetails = userDetailsService.findUserByUsername(username);
        if (userDetails != null) {
            if (grantedAuthorities != null && !grantedAuthorities.isEmpty()) {
                userDetails.getAuthorities().addAll(grantedAuthorities);
            }
        } else {
            //测试域用户在本地无关联用户数据时创建本地用户数据,用户数据可存储在数据库
            User user = new User();
            user.setUsername(username);
            user.setPassword(null);
            user.setName(username);
            user.setLocked(false);
            user.setAccountExpiringDate(DateUtils.addYears(new Date(), 1));
            user.setCredentialsExpiringDate(DateUtils.addYears(new Date(), 1));
            userService.save(user);
            userDetails = userDetailsService.findUserByUsername(username);
        }
        //生成token，并存放在redis中
        String token = UUID.randomUUID().toString();
        userDetails.setToken(token);
        redisTemplate.opsForValue().set(token, username, Duration.ofMinutes(30));
        return userDetails;
    }

}
